package org.biloxi.commands.changephase.events;

import org.biloxi.commands.Command;
import org.biloxi.commands.CommandEventDispatcher;
import org.biloxi.commands.Filter;
import org.biloxi.commands.Listener;
import org.biloxi.commands.changephase.ChangePhase;
import org.biloxi.commands.changephase.ChangePhase.Options;
import org.biloxi.commands.changephase.ChangePhase.Result;
import org.biloxi.commands.impl.EventDispatcherImpl;
import org.biloxi.model.GameState;
import org.biloxi.model.GameState.Phase;

public class PhaseEvent extends EventDispatcherImpl<Options,Result> {
	protected class EventRedirector extends EventDispatcherImpl<Options,Result> implements Listener<Options,Result>{
		public void handle(Command<Options,Result> src,Options opt, Result result, GameState gameState) {
			this.notifyListeners(src, opt, result,gameState);
		}
	}
	
	private final Phase _phase;

	public final CommandEventDispatcher<Options,Result> begins;
	//TODO add during
	public final CommandEventDispatcher<Options,Result> ends;
	
	public PhaseEvent(Phase p, Command<ChangePhase.Options,ChangePhase.Result> cpCmd) {
		_phase = p;
				
		EventRedirector b = new EventRedirector();
		cpCmd.do_(
			b, 
			new Filter<Result>(){
				public boolean allow(Result t) {
					return t.phase == _phase;
				} 
			}
		);
		begins = b;
		
		// if begins isn't specified, assume beginning
		begins.do_(new Listener<Options,Result>(){
			public void handle(Command<Options,Result> src,Options opt, Result result, GameState gameState) {
				PhaseEvent.this.notifyListeners(src, opt, result,gameState);
			}
		});
		
		EventRedirector e = new EventRedirector();
		cpCmd.do_(
			e, 
			new Filter<Result>(){
				public boolean allow(Result t) {
					return t.previousPhase == _phase;
				} 
			}
		);
		ends = e;
	}
	
	
}
